package com.base.exp

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.activity.result.ActivityResultLauncher
import androidx.core.net.toUri
import com.loyal.core.helper.UIHelper

fun Context.showToast(message: String) {
    UIHelper.toastShort(this, message)
}

fun Context.dpToPx(dip: Float): Int {
    val density = resources.displayMetrics.density
    return (dip * density + 0.5f * if (dip >= 0) 1 else -1).toInt()
}

fun Context?.canWriteSettings(launcher: ActivityResultLauncher<Intent>? = null): Boolean {
    if (null == this) return false
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        //大于等于23 请求权限
        if (!Settings.System.canWrite(this)) {
            val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
            intent.data = "package:$packageName".toUri()
            launcher?.launch(intent)
            return false
        }
    }
    return true
}

fun Context.action2SelfPermission() {
    try {
        val intent = Intent(Settings.ACTION_SETTINGS)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.data = Uri.fromParts("package", packageName, null)
        startActivity(intent)
    } catch (e: Exception) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.data = Uri.fromParts("package", packageName, null)
        startActivity(intent)
    }
}

/**是否拥有显示在应用上方权限*/
fun Context?.hasOverlaysPermission(): Boolean {
    if (null == this) return false
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Settings.canDrawOverlays(this)
    } else true
}
